$(function() {
	
	//验证
	validateInit();
	
	$('#basedataLevel1Table').bootstrapTable({
		data : getLevel1Datas(),
		striped : true, 
		cache : false, 
		pagination : true, 
		sortable : false, 
		sidePagination : "client",
		pageNumber : 1,
		pageSize : 10,
		pageList : [ 10, 25, 50, 100 ], 
		search : true, 
		strictSearch : false,
		//showColumns : true, 是否有选择列的那个选项
		clickToSelect : true,
		uniqueId : 'id',
		columns : [ 
		{
			field : 'level1Name',
			title : '大类名称'
		}],
		onClickRow : function(row ) {// 单击
			$("#level1NameInputHidden").val(row.level1Name);
			$("#level1IdHid").val(row.level1Id);
			$("#basedataLevel2Table").bootstrapTable("load", getLevel2Datas());
		} 
	});
	
	$("#basedataLevel1Table").bootstrapTable("hideColumn","id");
	$("#basedataLevel1Table tbody").css("cursor","pointer");
	
	//小类值管理
	$('#basedataLevel2Table').bootstrapTable({
		data : getLevel2Datas(),
		striped : true, 
		cache : false, 
		pagination : true, 
		sortable : false, 
		toolbar : "#basedatalevel2ToolBar",
		sidePagination : "client",
		pageNumber : 1,
		pageSize : 10,
		pageList : [ 10, 25, 50, 100 ], 
		search : true, 
		strictSearch : false,
		showColumns : true, //是否有选择列的那个选项
		clickToSelect : true,
		uniqueId : 'id',
		columns : [
			{
				checkbox : true,
			},{
	    	   field : 'level1Name',
	    	   title : '大类名称'
	       },{
	    	   field : 'level2Name',
	    	   title : '小类名称'
	       },{
	    	   field : 'level2Value',
	    	   title : '小类值'
	       },{
	    	   field : 'operate',
	    	   title : '操作'
	       }],
       onDblClickRow : function(row) {// 
    	   
       }
	});
	
	$("#basedataLevel2Table").bootstrapTable("hideColumn","id");
});

function validateInit() {

	$("#addBasedataLevel2Form").validate({
		rules : {
			level2Name : {
				required : true,
				remote : {
					url : "../basedata/query.action",
					type : "post",
					data : {
						"level1Name" : function() {
							return $("#level1NameInputHidden").val();
						},
						"level2Name" : function() {
							return $("#addBasedataLevel2Form [name='level2Name']").val();
						},
						"dataStatus" : "1"
					},
					dataFilter : function(data) {
						if (data == '[]') {//这个判断不可理解，用data.length和$.isEmptyObject()都不好使
							return true;
						}
						return false;
					}
				}
			}
		},
		messages : {
			level2Name : {
				remote : "此小类名已经存在"
			}
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-ok form-control-feedback my-tip-i"></i>';
			element.parent().append(myTipLabel);
			element.parent().parent().addClass('has-success');
		},
		errorPlacement : function(label, element) {
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-remove form-control-feedback my-tip-i"></i>'
							+'<label class="control-label my-tip-label">'
							+	label.text()
							+'</label>';
			element.addClass("error");
			element.parent().append(myTipLabel);
			element.parent().parent().addClass('has-error');
		}
	});
	
	$("#updateBasedataLevel2Form").validate({
		rules : {
			level2Name : {
				required : true,
				remote : {
					url : "../basedata/query.action",
					type : "post",
					data : {
						"level1Name" : function() {
							return $("#level1NameInputHidden").val();
						},
						"level2Name" : function() {
							return $("#updateBasedataLevel2Form [name='level2Name']").val();
						},
						"level2Value" : function() {
							return $("#updateBasedataLevel2Form [name='level2Value']").val();
						},
						"dataStatus" : "1"
					},
					dataFilter : function(data) {
						if (data == '[]') {//这个判断不可理解，用data.length和$.isEmptyObject()都不好使
							return true;
						}
						return false;
					}
				}
			}
		},
		messages : {
			level2Name : {
				remote : "此小类名已经存在"
			}
		},
		success : function(label, element) {// error是lavel标签，element是input标签
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-ok form-control-feedback my-tip-i"></i>';
			element.parent().append(myTipLabel);
			element.parent().parent().addClass('has-success');
		},
		errorPlacement : function(label, element) {
			labelReset(element);

			var myTipLabel = '<i class="glyphicon glyphicon-remove form-control-feedback my-tip-i"></i>'
							+'<label class="control-label my-tip-label">'
							+	label.text()
							+'</label>';
			element.addClass("error");
			element.parent().append(myTipLabel);
			element.parent().parent().addClass('has-error');
		}
	});
}

function getLevel1Datas() {
	var level1Datas;
	var level1Names = new Array();//为了删选出重复的大类值
	$.ajax({
		url: "../basedata/query.action",
		type: "post",
		async: false,//是为了内层ajax在之后访问
		data: {"dataStatus":"1"},
		success: function(data) {
			//默认显示第一个大类的所有小类
			if (data.length != 0) {
				
				$("#level1NameInputHidden").val(data[0].level1Name);
				$(data).each(function(index,obj){
					if (data.length == index) {
						return false; //break;
					}
					name = data[index].level1Name;
					while ($.inArray(name, level1Names) != -1){
						data.splice(index,1);//从index角标移除一个元素，就是移除数组中的此元素
						if (data.length == index) {
							return false; //break;
						}
						name = data[index].level1Name;
					}
					level1Names.push(name);
				});
			}
			level1Datas = data;
		},
		error: function() {
			toastr.error("获取基础代码信息出错，请联系管理员");
		}
	});
	return level1Datas;
}

function getLevel2Datas() {
	var level2Datas;
	var name = $("#level1NameInputHidden").val();
	if (isNull(name)) {
		var result = [];
		return result;
	}
	$.ajax({
		url: "../basedata/query.action",
		type: "post",
		async: false,
		data: {"level1Name" : name, "dataStatus":"1"},
		success: function(data) {
			$(data).each(function() {
				this.operate = '<button class="btn btn-primary btn-xs" onclick="updateBasedataLevel2(' + this.id + ')">修改</button>&nbsp;'
							+ 	'<button class="btn btn-danger btn-xs" onclick="singleDelete('+ this.id + ')">删除</button>';
			});
			level2Datas = data;
		},
		error: function() {
			toastr.error("获取基础代码小类信息出错，请联系管理员");
		}
	});
	return level2Datas;
}

function addBasedataLevel2() {
	formReset("#addBasedataLevel2Form");
	$("#addBasedataLevel2Form [name='level1Name']").val($("#level1NameInputHidden").val());
	$("#addBasedataLevel2Form [name='level1Name']").attr("disabled","disabled");
	$("#addBaseDataLevel2Modal").modal("show");
}

function addBasedataLevel2Save() {
	if(!$("#addBasedataLevel2Form").valid()) {
		return false;
	}
	$("#addBasedataLevel2Form [name='level1Name']").removeAttr("disabled");
	$.ajax({
		url : "../basedata/save.action",
		type : "post",
		data : $("#addBasedataLevel2Form").serialize(),
		success : function(data) {
			if (data.success == "true") {
				toastr.success("保存成功");
				$("#basedataLevel2Table").bootstrapTable("load", getLevel2Datas());
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
	$("#addBaseDataLevel2Modal").modal("hide");
}

function updateBasedataLevel2(id) {
	formReset("#updateBasedataLevel2Form");
	$("#updateBasedataLevel2Form [name='id']").val(id);
	$("#updateBasedataLevel2Form [name='level1Name']").val($("#level1NameInputHidden").val());
	$("#updateBasedataLevel2Form [name='level1Name']").attr("disabled","disabled");
	
	//填充小类名称和小类值(小类值如果有的话)
	$.ajax({
		url : "../basedata/query.action",
		type : "post",
		async : false,
		data : {"id": id},
		success: function(data) {
			//console.log(data);
			$("#updateBasedataLevel2Form [name='level1Id']").val(data[0].level1Id);
			$("#updateBasedataLevel2Form [name='level2Id']").val(data[0].level2Id);
			$("#updateBasedataLevel2Form [name='level2Name']").val(data[0].level2Name);
			$("#updateBasedataLevel2Form [name='level2Value']").val(data[0].level2Value);
			$("#updateBaseDataLevel2Modal").modal("show");
		},
		error: function() {
			toastr.error("获取小类信息失败，请联系管理员");
		}
	});
}

function updateBasedataLevel2Save() {
	if(!$("#updateBasedataLevel2Form").valid()) {
		return false;
	}
	
	
	//验证level1Id如果为1，则是数值类型，小类值必须有且必须为数值
	var myLevel1Id = $("#level1IdHid").val();
	if (myLevel1Id == "1") {
		var myLevel2Value = $("#updateBasedataLevel2Form [name='level2Value']").val();
		if (myLevel2Value == '' || myLevel2Value == null) {
			toastr.error("数值类型必须有小类值");
			return;
		}
		if (isNaN(myLevel2Value)) {
			toastr.error("数值类型的小类值必须是数字");
			return;
		}
	}
	$("#updateBasedataLevel2Form [name='level1Name']").removeAttr("disabled");//是为了取值
	$.ajax({
		url : "../basedata/update.action",
		type : "post",
		data : $("#updateBasedataLevel2Form").serialize(),
		success : function(data) {
			if (data.success == "true") {
				toastr.success("保存成功");
				$("#basedataLevel2Table").bootstrapTable("load", getLevel2Datas());
				$("#updateBaseDataLevel2Modal").modal("hide");
			} else {
				$("#updateBasedataLevel2Form [name='level1Name']").attr("disabled","disabled");
				toastr.error(data.msg);
			}
		},
		error: function() {
			toastr.error("提交到数据库发生错误，请联系管理员");
		}
	});
}

function singleDelete(id) {
	var basedataIds=new Array();
	basedataIds[0]=id;
	deleteCore(basedataIds);
}

function batchDelete() {
	var selectedBasedatas = $("#basedataLevel2Table").bootstrapTable('getSelections');
	if(selectedBasedatas.length == 0){
		toastr.error("请勾选你要删除的数据");
		return false;
	}
	var basedataIds = new Array();
	$(selectedBasedatas).each(function(index,basedata){
		basedataIds[index] = basedata.id;
	})

    deleteCore(basedataIds);
}
function deleteCore(basedataIds) {
	swal({
        title: "您确定要删除所选信息吗",
        text: "删除后将无法恢复，请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "删除",
        closeOnConfirm: false
    }, function () {
    	$.ajax({
    		url: "../basedata/batchDelete.action",
    		type: "post",
    		data: {"basedataIds":basedataIds},
    		success: function(data) {
    			if (data.success == "true") {
    				swal("删除成功", "您已经永久删除了所选信息。", "success");
    				$("#basedataLevel2Table").bootstrapTable("load",getLevel2Datas());
    			} else {
    				swal("删除失败", "后台业务处理发生错误，请联系管理员", "error");
    			}
    		},
    		error: function() {
    			swal("操作失败", "提交到数据库发生错误，请联系管理员。", "error");
    		}
    	});
    });
}